<?php

namespace app\admin\controller\jdy;

use app\common\controller\Backend;

use think\Session;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;

/**
 * 水电记录管理
 *
 * @icon fa fa-circle-o
 */
class Sdblog extends Backend
{
    
    /**
     * Sdblog模型对象
     * @var \app\admin\model\jdy\Sdblog
     */
    protected $model = null;

    const SDBIAO_ID = "__sdbiaoid__";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jdy\Sdblog;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $sdbiao_id = 0;
        $url = $_SERVER['HTTP_REFERER'];
        $dbiaoname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $sdbiao_id = $urls[$size - 1];
            Session::set(self::SDBIAO_ID, $sdbiao_id);
            $sdbiao = \app\admin\model\jdy\Sdbiao::get($sdbiao_id);
            if ($sdbiao) {
                $anchangname = "";
                if ($sdbiao) {
                    $anchang = \app\admin\model\jdy\Anchang::get($sdbiao->anchang_id);
                    if ($anchang) {
                        $anchangname = $anchang->name;
                    }
                }

                $dbiaoname = $anchangname." > ".$sdbiao->name." | ".$sdbiao->biaohao;
            }
        } else {
            Session::set(self::SDBIAO_ID, 0);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($sdbiao_id > 0) {
                $total = $this->model
                    ->with(['sdbiao'])
                    ->where($where)
                    ->where('sdbiao_id', $sdbiao_id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['sdbiao'])
                    ->where($where)
                    ->where('sdbiao_id', $sdbiao_id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            } else {
                $total = $this->model
                    ->with(['sdbiao'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['sdbiao'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            }

            $list = collection($list)->toArray();

            $lastrow = null;
            $xcbs = [];
            foreach ($list as $row) {
                if ($lastrow) {
                    $xcbs[] = intval($lastrow['cbs']) - intval($row['cbs']);
                }
                $lastrow = $row;
            }
            $xcbs[] = 0;

            $i = 0;
            foreach ($list as &$row) {
                $row['xcbs'] = $xcbs[$i];
                $i++;
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->view->assign("dbiaoname", $dbiaoname);
        $this->view->assign("ids", $sdbiao_id);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $sdbiao_id = Session::get(self::SDBIAO_ID);
        $this->view->assign("sdbiao_id", $sdbiao_id);

        $sdbiao = \app\admin\model\jdy\Sdbiao::get($sdbiao_id);
        $anchangname = "";
        if ($sdbiao) {
            $anchang = \app\admin\model\jdy\Anchang::get($sdbiao->anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }
        $this->view->assign("anchangname", $anchangname);

        $lastshu = 0;
        $lastlog = $this->model->where('sdbiao_id', $sdbiao_id)->order('id', 'DESC')->find();
        if ($lastlog) {
            $lastshu = $lastlog->cbs;
        }

        $this->view->assign("lastshu", $lastshu);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $sdbiao_id = Session::get(self::SDBIAO_ID);
        $this->view->assign("sdbiao_id", $sdbiao_id);

        $sdbiao = \app\admin\model\jdy\Sdbiao::get($sdbiao_id);
        $anchangname = "";
        if ($sdbiao) {
            $anchang = \app\admin\model\jdy\Anchang::get($sdbiao->anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }
        $this->view->assign("anchangname", $anchangname);

        $lastshu = 0;
        $lastlog = $this->model->where('sdbiao_id', $sdbiao_id)->where('id', '<', $ids)->order('id', 'DESC')->find();
        if ($lastlog) {
            $lastshu = $lastlog->cbs;
        }

        $this->view->assign("lastshu", $lastshu);

        return $this->view->fetch();
    }

    public function chart()
    {
        $ids = 0;
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $ids = $urls[$size - 1];
        }

        $row = \app\admin\model\jdy\Sdbiao::get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        if ($this->request->isPost()) {
            if (empty($_POST['dateInfo'])) {
                $this->error("請選擇日期范围");
            }
            $dateInfo = explode(' - ', $_POST['dateInfo']);
            $from = $dateInfo[0];
            $to = $dateInfo[1];

            $list = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $row['id'])
                ->where('create_time', '>', $from)
                ->where('create_time', '<', $to)
                ->order('id', 'DESC')
                ->select();
            $list = collection($list)->toArray();

            $lastrow = null;
            $xcbs = [];
            $xdata = [];
            foreach ($list as $row0) {
                if ($lastrow) {
                    $xcbs[] = intval($lastrow['cbs']) - intval($row0['cbs']);
                }
                $xdata[] = $row0['create_time'];
                $lastrow = $row0;
            }
            $xcbs[] = 0;

            $i = 0;
            foreach ($list as &$row0) {
                $row0['xcbs'] = $xcbs[$i];
                $i++;
            }

            $data = array(
                "list" => array_reverse($list),
                "xdata" => array_reverse($xdata),
                "ydata" => array_reverse($xcbs)
            );

            $this->success(__('查询成功'), null, $data);
        }

        $from = date("Y-m-d H:i:s", strtotime("-7 days", time()));
        $to = date("Y-m-d H:i:s", time());

        $list = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $row['id'])
            ->where('create_time', '>', $from)
            ->where('create_time', '<', $to)
            ->order('id', 'DESC')
            ->select();
        $list = collection($list)->toArray();

        $lastrow = null;
        $xcbs = [];
        $xdata = [];
        foreach ($list as $row0) {
            if ($lastrow) {
                $xcbs[] = intval($lastrow['cbs']) - intval($row0['cbs']);
            }
            $xdata[] = $row0['create_time'];
            $lastrow = $row0;
        }
        $xcbs[] = 0;

        $i = 0;
        foreach ($list as &$row0) {
            $row0['xcbs'] = $xcbs[$i];
            $i++;
        }

        $anchangname = "";
        if ($row) {
            $anchang = \app\admin\model\jdy\Anchang::get($row->anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
            }
        }
        $row = $row->toArray();
        $row['anchangname'] = $anchangname;

        $this->view->assign("ids", $ids);
        $this->view->assign("from", $from);
        $this->view->assign("to", $to);
        $this->view->assign("ydata", array_reverse($xcbs));
        $this->view->assign("xdata", array_reverse($xdata));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
